package Controllers;

import DB.DBCheckpoint;
import DB.DBRound;
import Models.Checkpoint;
import Models.Round;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

public class RoundController implements ControllerInterface<Round>
{
	public RoundController ()
	{}

	public int insert(Round round)
	{
		DBRound dbr = new DBRound();
		int roundNo = dbr.insert(round.exportData());

		round.setRoundNo(roundNo);
		round.setRoundNoOnCheckpoints();
		insertDependent(round.getCheckpoints());

		return roundNo;
	}

	public void insertDependent(ArrayList<? extends DB.RowInterface> data)
	{
		DBCheckpoint dbc = new DBCheckpoint();
		ArrayList<HashMap> rowsData = new ArrayList<HashMap>();
		Iterator<Checkpoint> i = ((ArrayList<Checkpoint>)data).iterator();
		while(i.hasNext())
		{
			Checkpoint checkpoint = i.next();
			if(dbc.alreadyExists(checkpoint.getCheckpointNo()))
			{
				dbc.update(checkpoint.exportData(), "checkpointNo = "+checkpoint.getCheckpointNo());
			}
			else
			{
				rowsData.add(checkpoint.exportData());
			}
		}
		if(rowsData.size() > 0)
		{
			dbc.insert(rowsData);
		}
	}

	public Round find(int id)
	{
		DBRound dbr = new DBRound();
		return dbr.fetchByNo(id);
	}

	public int update(Round round, String where)
	{
		updateDependent(round.getCheckpoints(), null);

		DBRound dbr = new DBRound();
		return dbr.update(round.exportData(), where);
	}

	public void updateDependent(ArrayList<? extends DB.RowInterface> data, String where)
	{
		DBCheckpoint dbc = new DBCheckpoint();
		Iterator<Checkpoint> i = ((ArrayList<Checkpoint>)data).iterator();
		while(i.hasNext())
		{
			Checkpoint checkpoint = i.next();
			if(dbc.alreadyExists(checkpoint.getCheckpointNo()))
			{
				dbc.update(checkpoint.exportData(), "checkpointNo = "+checkpoint.getCheckpointNo());
			}
			else
			{
				dbc.insert(checkpoint.exportData());
			}
		}
	}

	public int delete(int id)
	{
		DBRound dbr = new DBRound();
		return dbr.deleteByNo(id);
	}

	public ArrayList<Round> fetchAll()
	{
		DBRound dbc = new DBRound();
		return dbc.fetchAll();
	}
}